package net.edu_soft.ec.asset.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.edu_soft.ec.asset.constant.EduConstant;
import net.edu_soft.ec.asset.mapper.PermissionMapper;
import net.edu_soft.ec.asset.pojo.Permission;
import net.edu_soft.ec.asset.pojo.PermissionExample;
import net.edu_soft.ec.asset.service.PermissionService;
import net.edu_soft.ec.asset.service.RolePermissionService;
import net.edu_soft.ec.common.exception.OperationException;
import net.edu_soft.ec.common.exception.ParameterException;
import net.edu_soft.ec.common.util.PuingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
        注入角色权限关系业务
     */
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public Permission find(Integer id) {
        PuingUtil.notNullByZero(id, "权限管理：查询的id不能为空或者小于等于0");
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<Permission> findList(String name, Integer pageNum, Integer pageSize) {
        PuingUtil.notNullByInt("权限管理：分页参数为空或小于等于0", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        PermissionExample example = new PermissionExample();
        PermissionExample.Criteria criteria = example.createCriteria();
        //不为空则根据名称模糊查询
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name.trim() + "%");
        }

        List<Permission> permissions = permissionMapper.selectByExample(example);
        PageInfo<Permission> pageInfo = new PageInfo<>(permissions);
        return pageInfo;
    }


    @Override
    public int save(Permission permission, Integer code) {
        permission = check(permission, code);
        if (sel(permission.getName(),2) != null) {
            throw new ParameterException("权限管理：存在该权限：" + permission.getName());
        }
        return permissionMapper.insertSelective(permission);
    }

    @Override
    public int update(Permission permission, Integer code) {
        if (permission == null) {
            throw new ParameterException("权限管理：修改的权限主体信息不能为空");
        }
        PuingUtil.notNullByZero(permission.getPermissionId(), "权限管理：权限id不能为空或者小于等于0");
        if (permissionMapper.selectByPrimaryKey(permission.getPermissionId()) == null) {
            throw new ParameterException("权限管理：修改的权限id查询不到信息");
        }
        permission = check(permission, code);
        //判断查询出来的权限id和要修改的id是否一致，不一致则存在相同的权限
        if (sel(permission.getName(),2).getPermissionId() != permission.getPermissionId()) {
            throw new ParameterException("权限管理：修改失败，存在相同的权限名：" + permission.getName() + ",id: " + permission.getPermissionId());
        }
        return permissionMapper.updateByPrimaryKeySelective(permission);
    }

    @Override
    public int del(String ids, Integer isDel) {
        int i = 0;
        //删除
        if (isDel == 1  && isDel != null) {
            //提取id
            List<Integer> list = PuingUtil.getNumber(ids);
            //循环查询
            for (Integer id : list) {
                //查询是否存在
                Permission permission = sel(id+"",1);
                if(permission==null){
                    throw new ParameterException("权限管理：权限主体信息不能为空,id: "+id);
                }
                permission.setStatus(EduConstant.STATUS_ONE);//1删除
                i = permissionMapper.updateByPrimaryKeySelective(permission);
            }
        }
        return i;
    }

    @Override
    public List<Permission> findByRoleId(Integer roleId) {
        List<Integer> permissionIds = rolePermissionService.selPermissionIds(roleId);
        if(permissionIds==null || permissionIds.size()<=0){
            throw new OperationException("查询角色权限失败，该角色没有赋予权限，角色id"+roleId);
        }
        //查询权限信息
        List<Permission> permissions = permissionMapper.selPermissions(permissionIds);
        return permissions;
    }

    @Override
    public List<Permission> findByParentId(Integer parentId) {
        PuingUtil.notNullByZero(parentId, "权限管理：父id不能为空或者小于等于0");
        PermissionExample example = new PermissionExample();
        PermissionExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);//父id
        List<Permission> permissions = permissionMapper.selectByExample(example);
        return permissions;
    }

    private Permission check(Permission permission, Integer code) {
        if (permission == null) {
            throw new ParameterException("权限管理：权限主体信息不能为空");
        }
        Assert.hasLength(permission.getName(), "权限管理：名称不能为空");
        PuingUtil.notNullByZero(code, "权限管理：菜单权限码不能为空或者小于等于0");
        if (code == 1) {//菜单
            permission.setType("menu");//设置类型
        } else if (code == 2) {//权限
            Assert.hasLength(permission.getUrl(), "权限管理：资源路径url不能为空");
            Assert.hasLength(permission.getPerCode(), "权限管理：权限拦截码不能为空");
            PuingUtil.notNullByZero(code, "权限管理：权限的父id即菜单id不能为空或者小于等于0");
            permission.setType("permission");//设置类型
        } else {
            throw new ParameterException("权限管理：菜单权限码错误 1为菜单 2为权限");
        }
        permission.setStatus(EduConstant.STATUS_ZREO);//设置状态
        return permission;
    }


    private Permission sel(String idOrName,int code) {
        Assert.hasLength(idOrName, "权限管理：名称不能为空");
        PermissionExample example = new PermissionExample();
        PermissionExample.Criteria criteria = example.createCriteria();
        //id和状态
        if(code==1){//权限id
            int id = Integer.parseInt(idOrName);
            PuingUtil.notNullByZero(id, "权限管理：权限id不能为空或者小于等于0");
            criteria.andPermissionIdEqualTo(id);
        }else { //名
            criteria.andNameEqualTo(idOrName);
        }
        criteria.andStatusEqualTo(EduConstant.STATUS_ZREO);
        List<Permission> permissions = permissionMapper.selectByExample(example);
        if (permissions.size() > 0) {
            return permissions.get(0);
        }
        return null;
    }

}
